package com.fuhaiwei.domain.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.fuhaiwei.basic.hibernate.HibernateSessionFactory;
import com.fuhaiwei.domain.dao.UserDao;
import com.fuhaiwei.domain.model.User;

public class UserDaoImpl implements UserDao {

	private HibernateSessionFactory sessionFactory;

	public void save(User user) {
		getSession().save(user);
	}

	public User get(int id) {
		return (User) getSession().get(User.class, id);
	}

	public List findByUsername(String username) {
		return getSession()
				.createQuery("from User u where u.username = :username")
				.setParameter("username", username).list();
	}

	public List findAll() {
		return getSession().createQuery("from User").list();
	}

	public void update(User user) {
		getSession().update(user);
	}

	public void delete(int id) {
		getSession().delete(get(id));
	}

	public void delete(User user) {
		getSession().delete(user);
	}

	public Transaction beginTransaction() {
		return sessionFactory.getSession().beginTransaction();
	}

	public void closeSession() {
		sessionFactory.closeSession();
	}

	public void setSessionFactory(HibernateSessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getSession() {
		return sessionFactory.getSession();
	}

}